// pages/classanalysis/classanalysis.js
import https from '../../utils/Newrequests'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        launchFlag: true,
        selectMenu: {},
        height: null,
        switch: true,
        classInfo: {},
        totalScoreFlag: true,
        criticalGrowthFlag: true,
        classReferenceNumber: 0,
        classAverageScore: 0,
        classHighestScore: 0,
        classAverageScoreRank: 0,
        classMinimumScore: 0,
        lineOnes: 0,
        lineTwos: 0,
        schoolReferenceNumber: 0,
        schoolAverageScore: 0,
        schoolMaximumScore: 0,
        classAverageScoreRanking: 0,
        classLowestScore: 0,
        datalist: {},
        criticalGrowthData: {},
        onlineComparison: {},
        scoringRateData: [],
        aline: null,
        bline: null,
        averageScoreData: [],
        averageScoreX: [],
        averageScoreY: [],
        fractionalRangeData: [],
        goOnlineFlag: true,
        yData: [
            {
                name: '班级',
                data: [10, 20, 30, 40]
            },
            {
                name: '学校',
                data: [1, 2, 3, 4]
            }
        ],
        xData: ['优秀', '良好', '及格', '低分'],
        menuList: [
        ],
        endowFlag: 1,
        averageScoreX: [],
        averageScoreY: [],
        averageScoreData: [],
        segmentInterval: 10,
        scoreType: 2,
        examId: null,
        selectTypeName: '',
        subjectId: -1
    },
    navigateToNewSelectTranscripts() {
        // 获取当前 examId 参数
        const examId = this.data.examId;
        const selectTypeName = this.data.selectTypeName;
        // 跳转到目标页面并传递参数
        wx.navigateTo({
            url: `/pages/Newselecttranscripts/Newselecttranscripts?id=${examId}&selectTypeName=${selectTypeName}`,
        });
    },
    changeMenu(e) {
        const selectedItem = e.detail;  // 子组件传上来的 {id, name, endowScore}
        const subjectId = selectedItem.id;
        const subjectName = selectedItem.name;
        const endowFlag = selectedItem.endowScore;
        this.setData({
            subjectId,
            subjectName,
            endowFlag
        });
        // 判断 id 是否为负数
        if (subjectId < 0) {
            this.setData({
                scoreType: 2
            });
            // 如果 id 是负数，则不传 subjectId
            this.getSchoolScoreInfo(this.data.examId, this.data.subjectGroup, this.data.endowFlag, this.data.classId);
            this.getSchoolScoreCompare(this.data.examId, this.data.subjectGroup, this.data.endowFlag, this.data.classId)
            this.getComparison(this.data.examId, this.data.subjectGroup, this.data.endowFlag, this.data.segmentInterval, this.data.scoreType, this.data.classId)
            this.getScoringAverage(this.data.examId, this.data.subjectGroup, this.data.endowFlag, this.data.classId)
            this.getCriticalStudent(this.data.examId, this.data.subjectGroup, this.data.endowFlag, this.data.classId) //临界生
            this.getOnlineStatus(this.data.examId, this.data.subjectGroup, this.data.endowFlag, this.data.classId);

        } else {
            this.setData({
                scoreType: 1
            });
            // 否则传递 subjectId
            this.getSchoolScoreInfo(this.data.examId, this.data.subjectGroup, this.data.endowFlag, this.data.classId, subjectId);
            this.getSchoolScoreCompare(this.data.examId, this.data.subjectGroup, this.data.endowFlag, this.data.classId, subjectId);
            this.getComparison(this.data.examId, this.data.subjectGroup, this.data.endowFlag, this.data.segmentInterval, this.data.scoreType, this.data.classId, subjectId)
            this.getScoringAverage(this.data.examId, this.data.subjectGroup, this.data.endowFlag, this.data.classId, subjectId);
            this.getCriticalStudent(this.data.examId, this.data.subjectGroup, this.data.endowFlag, this.data.classId, subjectId)//临界生
            // this.getOnlineStatus(this.data.examId, this.data.subjectGroup, this.data.endowFlag, this.data.classId, subjectId);
        }
        console.log("切换科目：", subjectId, subjectName, endowFlag);
    },
    changeoverSwitch() {
        this.setData({
            switch: !this.data.switch
        })
    },
    //科目列表
    async getExamSubjectList(examId, subjectGroup, classId) {
        let options = {
            url: '/analysis/total/score/getExamSubjectList',
            method: 'get',
            data: { examId, subjectGroup, classId },
            header: { "content-type": "application/json;charset=UTF-8" },
        };

        try {
            // 发送请求
            let res = await https(options);

            // 如果请求成功，更新科目列表
            if (res.data.code === 200) {
                console.log(res.data.data, '考试概览数据');

                this.setData({
                    menuList: res.data.data || [],
                });
            } else {
                // wx.showToast({
                //     title: res.data.msg || '科目列表请求失败',
                //     icon: 'none',
                // });
            }
        } catch (error) {
            console.error('科目列表请求失败:', error);
            // wx.showToast({
            //     title: '科目列表请求失败',
            //     icon: 'none',
            // });
        }
    },
    //平均分对比
    async getSchoolScoreCompare(examId, subjectGroup, endowFlag, classId, subjectId = null) {
        // 组装基础参数
        let data = { examId, subjectGroup, endowFlag, classId };

        // 只有 subjectId 有值时才加入
        if (subjectId !== undefined && subjectId !== null && subjectId !== '') {
            data.subjectId = subjectId;
        }
        let options = {
            url: '/analysis/total/score/schoolScoreCompare',
            method: 'get',
            data,
            header: { "content-type": "application/json;charset=UTF-8" },
        };

        try {
            // 发送请求
            let res = await https(options);

            // 如果请求成功，过滤数据并更新页面
            if (res.data.code === 200) {
                console.log(res.data.data, '学校成绩比较数据');

                // 过滤掉索引为 0 和 1 的数据
                const filteredData = res.data.data.filter((item, index) => index > 1);
                console.log(filteredData, '过滤后的数据');

                // 提取 xData 和 yData 用于图表
                const xData = filteredData.map(item => item[Object.keys(item)[0]].className); // 提取 className
                const yData = filteredData.map(item => item[Object.keys(item)[0]].avgScore);
                // console.log(xData, "ssss");

                // 提取 list 用于表格显示
                // 这里获取 filteredData 里的每一个对象
                const list = filteredData.map(item => {
                    // 遍历每个对象的键（例如 33 或 31）
                    return Object.keys(item).map(key => {
                        const currentClass = item[key];  // 当前班级数据
                        return {
                            className: currentClass.className,  // 班级名称
                            people: currentClass.studentCount,  // 学生人数
                            maxScore: currentClass.highScore,  // 最高分
                            avgScore: currentClass.avgScore,   // 平均分
                            rank: currentClass.avgScoreRank,   // 排名
                        };
                    }).flat();  // 使用 flat() 将结果扁平化为一个数组
                }).flat();  // 再次扁平化外层数组

                console.log(list, "转换后的列表");

                // 更新数据
                this.setData({
                    averageScoreX: xData,
                    averageScoreY: yData,
                    averageScoreData: list
                });
            } else {
                // wx.showToast({
                //     title: res.data.msg || '平均分对比请求失败',
                //     icon: 'none',
                // });
            }
        } catch (error) {
            console.error('平均分对比请求失败:', error);
            // wx.showToast({
            //     title: '平均分对比请求失败',
            //     icon: 'none',
            // });
        }
    },
    //考试概览
    async getSchoolScoreInfo(examId, subjectGroup, endowFlag, classId, subjectId = null) {
        // 组装基础参数
        let data = { examId, subjectGroup, endowFlag, classId };

        // 只有 subjectId 有值时才加入
        if (subjectId !== undefined && subjectId !== null && subjectId !== '') {
            data.subjectId = subjectId;
        }
        let options = {
            url: '/analysis/total/score/schoolScoreInfo',
            method: 'get',
            data,
            header: { "content-type": "application/json;charset=UTF-8" },
        };

        try {
            // 发送请求
            let res = await https(options);

            // 请求成功，更新页面数据
            if (res.data.code === 200) {
                console.log(res.data.data, '学校成绩信息');
                // 提取 scoreLines 中的一档线和二档线
                const scoreLines = res.data.data.scoreLines;
                const schoolAverageScoreRanking1 = scoreLines.length > 0 ? scoreLines[0].onlineNumber : 0; // 一档线人数
                const schoolAverageScoreRanking2 = scoreLines.length > 1 ? scoreLines[1].onlineNumber : 0; // 二档线人数

                const onlineName1 = scoreLines.length > 0 ? scoreLines[0].onlineName : ''; // 一档线名称
                const onlineName2 = scoreLines.length > 1 ? scoreLines[1].onlineName : ''; // 二档线名称
                if (res.data.code === 200) {
                    const scoreLines = res.data.data.scoreLines || [];
                    this.setData({
                        // 原有数据
                        numberOfJointExaminations: res.data.data.numberOfJointExaminations,
                        classReferenceNumber: res.data.data.myClassStats.studentCount,
                        averageScoreOfTheJointExamination: res.data.data.averageScoreOfTheJointExamination,
                        classAverageScore: res.data.data.myClassStats.avgScore,
                        theHighestScoreInTheJointExam: res.data.data.theHighestScoreInTheJointExam,
                        classHighestScore: res.data.data.myClassStats.highScore,
                        schoolAverageScoreRanking: res.data.data.schoolAverageScoreRanking,
                        classAverageScoreRank: res.data.data.myClassStats.avgScoreRank,
                        onLine1Score: res.data.data.onLine1Score,
                        aline: res.data.data.aline,
                        schoolExcellenceRate: res.data.data.schoolExcellenceRate,
                        schoolPassingRate: res.data.data.schoolPassingRate,
                        classMinimumScore: res.data.data.myClassStats.lowScore,
                        schoolReferenceNumber: res.data.data.mySchoolStats.studentCount,
                        schoolAverageScore: res.data.data.mySchoolStats.avgScore,
                        schoolMaximumScore: res.data.data.mySchoolStats.highScore,
                        classAverageScoreRanking: res.data.data.mySchoolStats.avgScoreRank,
                        classLowestScore: res.data.data.mySchoolStats.lowScore,
                        scoreLines
                    });
                }

                // this.setData({
                //     // 更新页面的数据
                //     numberOfJointExaminations: res.data.data.numberOfJointExaminations,
                //     classReferenceNumber: res.data.data.mySchoolStats.studentCount,
                //     averageScoreOfTheJointExamination: res.data.data.averageScoreOfTheJointExamination,
                //     classAverageScore: res.data.data.mySchoolStats.avgScore,
                //     theHighestScoreInTheJointExam: res.data.data.theHighestScoreInTheJointExam,
                //     classHighestScore: res.data.data.mySchoolStats.highScore,
                //     schoolAverageScoreRanking: res.data.data.schoolAverageScoreRanking,
                //     classAverageScoreRank: res.data.data.mySchoolStats.avgScoreRank,
                //     onLine1Score: res.data.data.onLine1Score,
                //     aline: res.data.data.aline,
                //     schoolExcellenceRate: res.data.data.schoolExcellenceRate,
                //     schoolPassingRate: res.data.data.schoolPassingRate,
                //     classMinimumScore: res.data.data.mySchoolStats.lowScore,
                //     schoolReferenceNumber: res.data.data.examStats.studentCount,
                //     schoolAverageScore: res.data.data.examStats.avgScore,
                //     schoolMaximumScore: res.data.data.examStats.highScore,
                //     classAverageScoreRanking: res.data.data.examStats.avgScoreRank,
                //     classLowestScore: res.data.data.examStats.lowScore,
                //     schoolAverageScoreRanking1, // 一档线人数
                //     schoolAverageScoreRanking2, // 二档线人数
                //     onlineName1, // 一档线名称
                //     onlineName2, // 二档线名称
                // });
            } else {
                // wx.showToast({
                //     title: res.data.msg || '考试概览请求失败',
                //     icon: 'none',
                // });
            }
        } catch (error) {
            console.error('考试概览请求失败:', error);
            // wx.showToast({
            //     title: '考试概览请求失败',
            //     icon: 'none',
            // });
        }
    },
    // 上线对比数据请求
    // async getOnlineStatus(examId, subjectGroup, endowFlag, classId,) {
    //     let options = {
    //         url: '/analysis/line/online/peopleCompare',
    //         method: 'get',
    //         data: { examId, subjectGroup, endowFlag, classId },
    //         header: { "content-type": "application/json;charset=UTF-8" },
    //     };

    //     try {
    //         let res = await https(options);
    //         if (res.data.code === 200) {
    //             const raw = res.data.data || [];
    //             // 处理成 [{name, list}, ...] 结构
    //             const linesData = raw.map(obj => {
    //                 const key = Object.keys(obj)[0];
    //                 let list = obj[key] || [];

    //                 // 过滤掉“特控(一本)线”和“本科(二本)线”中的索引为0的数据

    //                 // 保存索引为0的顶部信息，用来显示在顶部区域
    //                 const firstClassData = list[0] || {};  // 获取第一个班级数据
    //                 const firstClassInfo = firstClassData[Object.keys(firstClassData)[0]] || [];  // 获取该班级的数据数组
    //                 const classInfo = firstClassInfo[0] || {};  // 提取数组中的第一个元素，即班级的实际数据
    //                 console.log(classInfo, "哈哈哈哈哈哈");

    //                 const topData = {
    //                     onLineScore: classInfo.lineScore || 0,  // 分数线
    //                     onReferenceNumber: classInfo.peopleNum || 0,  // 参考人数
    //                     onLineNum: classInfo.fullScoreLineNum || 0,  // 上线人数
    //                     onLineRate: classInfo.onlineRate || 0,   // 上线率
    //                 };

    //                 console.log(topData, 'topData');  // 打印出获取的顶部信息

    //                 // 设置顶部数据
    //                 this.setData({
    //                     datainfo: topData,
    //                 });

    //                 // 去掉索引为0的数据，用于表格展示
    //                 list = list.slice(1);


    //                 return {
    //                     name: key,
    //                     list: list  // 班级数据数组
    //                 };
    //             });

    //             this.setData({
    //                 linesData,        // 所有分数线数据
    //                 currentIndex: 0   // 默认选中第一条
    //             });
    //         } else {
    //             wx.showToast({ title: res.data.msg || '上线对比请求失败', icon: 'none' });
    //         }
    //     } catch (error) {
    //         console.error('上线对比请求失败:', error);
    //         wx.showToast({ title: '上线对比请求失败', icon: 'none' });
    //     }
    // },
    //得分率对比
    async getScoringAverage(examId, subjectGroup, endowFlag, classId, subjectId = null) {
        // 组装基础参数
        let data = { examId, subjectGroup, endowFlag, classId };

        // 只有 subjectId 有值时才加入
        if (subjectId !== undefined && subjectId !== null && subjectId !== '') {
            data.subjectId = subjectId;
        }
        let options = {
            url: '/analysis/total/score/schoolScoreCompare',
            method: 'get',
            data,
            header: { "content-type": "application/json;charset=UTF-8" },
        };

        try {
            let res = await https(options);

            // 打印原始数据，检查返回结果
            console.log(res.data.data, '原始数据');

            if (res.data.code === 200) {
                // 过滤数据
                const filterComparisonData = res.data.data.filter((item, index) => index > 0);
                console.log(filterComparisonData, '过滤后的数据');

                // 如果过滤后的数据为空，打印提示
                if (filterComparisonData.length === 0) {
                    console.log('过滤后的数据为空');
                }

                let yDataSchool = [];
                let yDataClass = [];

                let schoolData = filterComparisonData[0]; // 索引为0的是学校数据
                const schoolName = Object.keys(schoolData)[0]; // 学校名称作为键
                let schoolInfo = schoolData[schoolName]; // 获取学校数据

                console.log(schoolInfo, '学校数据');

                // 校验学校数据并处理
                if (schoolInfo && schoolInfo.schoolName) {
                    if (schoolInfo && schoolInfo.schoolName) {
                        yDataSchool = [
                            { schoolName: schoolInfo.schoolName, type: "优秀率", value: (Number(schoolInfo.excellentRate) * 100).toFixed(2) },
                            { schoolName: schoolInfo.schoolName, type: "良好率", value: (Number(schoolInfo.goodRate) * 100).toFixed(2) },
                            { schoolName: schoolInfo.schoolName, type: "及格率", value: (Number(schoolInfo.passRate) * 100).toFixed(2) },
                            { schoolName: schoolInfo.schoolName, type: "低分率", value: (Number(schoolInfo.lowScoreRate) * 100).toFixed(2) }
                        ];
                    }

                }
                const filterComparisonDataClass = filterComparisonData.filter((item, index) => index > 0);
                // 获取班级数据
                filterComparisonDataClass.forEach(item => {
                    Object.keys(item).forEach(classKey => {
                        let classData = item[classKey];
                        if (classData && classData.className) {
                            yDataClass.push({
                                className: classData.className,
                                excellentRate: (Number(classData.excellentRate) * 100).toFixed(2),
                                goodRate: (Number(classData.goodRate) * 100).toFixed(2),
                                passRate: (Number(classData.passRate) * 100).toFixed(2),
                                lowScoreRate: (Number(classData.lowScoreRate) * 100).toFixed(2),
                                excellentCount: classData.excellentCount,
                                goodCount: classData.goodCount,
                                passCount: classData.passCount,
                                lowScoreCount: classData.lowScoreCount
                            });
                        }
                    });
                });
                console.log(yDataSchool, "yDataSchool");
                console.log(yDataClass, "yDataClass");

                // 更新页面数据
                this.setData({
                    xDataSSSS: ['优秀', '良好', '及格', '低分'],
                    yDataSchool: yDataSchool,
                    yDataClass: yDataClass
                });

            } else {
                // wx.showToast({
                //     title: res.data.msg || '得分率对比请求失败',
                //     icon: 'none',
                // });
            }
        } catch (error) {
            console.error('得分率对比请求失败:', error);
            // wx.showToast({
            //     title: '得分率对比请求失败',
            //     icon: 'none',
            // });
        }
    },
    // 临界生数据请求
    async getCriticalStudent(examId, subjectGroup, endowFlag, classId, subjectId = null) {
        console.log("1");

        // 组装基础参数，注意这里 key 改成 isEndow
        let data = { examId, subjectGroup, isEndow: endowFlag, classId };
        // 只有 subjectId 有值时才加入
        if (subjectId !== undefined && subjectId !== null && subjectId !== '') {
            data.subjectId = subjectId;
        }
        let options = {
            url: '/analysis/line/critical/students/complete',
            method: 'post',
            data,
            header: { "content-type": "application/json;charset=UTF-8" },
        };

        try {
            let res = await https(options);
            if (res.data.code === 200) {
                const raw = res.data.data || [];

                // 转换格式
                const linesDataS = raw.map(line => {
                    const students = line.students.map(stu => {
                        // 1. 总分赋分展示
                        // let scoreStr = `${stu.totalScore}`;
                        // let scoreColor = ''; // 括号颜色
                        // if (stu.totalContribution > 0) {
                        //     scoreStr += ` (+${stu.totalContribution})`; // 拼接+号
                        //     scoreColor = 'red';
                        // } else if (stu.totalContribution < 0) {
                        //     scoreStr += ` (${stu.totalContribution})`; // 直接展示负数
                        //     scoreColor = 'green';
                        // } // =0 时只显示总分
                        let mainScore = `${stu.totalScore}`;
                        let contributionStr = '';
                        let scoreColor = '';

                        if (stu.totalContribution > 0) {
                            contributionStr = `(+${stu.totalContribution})`;
                            scoreColor = 'red';
                        } else if (stu.totalContribution < 0) {
                            contributionStr = `(${stu.totalContribution})`;
                            scoreColor = 'green';
                        }
                        // 2. 弱势科目
                        const weakSubjects = (stu.subjectScores || [])
                            .filter(s => s.contribution <= -10)
                            .map(s => s.examSubjectName)
                            .join("、") || "无";

                        // 3. 临界类型
                        const criticalType = stu.isPass === 1 ? "线上" : "线下";
                        return {
                            name: stu.studentName,
                            // scoreStr,           // 总分赋分展示
                            mainScore,
                            contributionStr,
                            scoreColor,
                            weakSubjects,
                            criticalType
                        };
                    });

                    // 区间范围 totalScore ± 10（取第一个学生的分数做区间）
                    let rangeStr = "";
                    if (line.subjects.length > 0) {
                        const tScore = line.subjects[0].lineScore;
                        rangeStr = `${tScore - 10} - ${tScore + 10}`;
                    }

                    return {
                        name: line.scoreLineTypeName,
                        rangeStr,
                        criticalNum: line.students.length,
                        students
                    };
                });

                // 默认展示第一组
                this.setData({
                    linesDataS,
                    currentIndexs: 0,
                    datainfoS: {
                        onlineRangeScore: linesDataS[0]?.rangeStr || "",
                        criticalNum: linesDataS[0]?.criticalNum || 0
                    },
                    currentList: linesDataS[0]?.students || []
                });

            } else {
                // wx.showToast({ title: res.data.msg || '临界生请求失败', icon: 'none' });
            }
        } catch (error) {
            console.error('临界生请求失败:', error);
            // wx.showToast({ title: '临界生请求失败', icon: 'none' });
        }
    },

    //分数段对比
    async getComparison(examId, subjectGroup, endowFlag, segmentInterval, scoreType, classId, subjectId = null,) {
        // 组装基础参数
        let data = { examId, subjectGroup, endowFlag, segmentInterval, scoreType, classId };

        // 只有 subjectId 有值时才加入
        if (subjectId !== undefined && subjectId !== null && subjectId !== '') {
            data.subjectId = subjectId;
        }
        let options = {
            url: '/analysis/total/score/scoreSegmentDistribution',
            method: 'get',
            data,
            header: { "content-type": "application/json;charset=UTF-8" },
        };

        try {
            // 发送请求
            let res = await https(options);
            // 如果请求成功，更新科目列表
            if (res.data.code === 200) {
                console.log(res.data.data, '分数段对比数据');
                const filterComparisonData = res.data.data.filter((item, index) => index > 1);
                console.log(filterComparisonData, "过滤后分数段对比的数据");
                // 处理数据：生成班级列表和表头
                const fractionalRangeHead = [];
                const fractionalRangeData = [];

                filterComparisonData.forEach((classData) => {
                    const classId = Object.keys(classData)[0]; // 获取班级ID
                    const segments = classData[classId]; // 获取班级的分数段数据
                    // console.log(classId, "班级id");
                    // console.log(segments, "班级分段数据");

                    // 遍历每个班级的分数段
                    segments.forEach((segment) => {
                        // 如果header中没有当前的segmentInfo，则添加
                        if (!fractionalRangeHead.includes(segment.segmentInfo)) {
                            fractionalRangeHead.push(segment.segmentInfo);
                        }
                    });

                    // 生成班级的数据行
                    const rowData = { school: classId }; // 班级ID
                    segments.forEach((segment, index) => {
                        rowData[fractionalRangeHead[index]] = segment.sameScoreNumber; // 按照分数段添加对应的人数
                    });
                    fractionalRangeData.push(rowData); // 将当前班级的行数据添加到列表
                });

                // 更新页面的数据
                this.setData({
                    fractionalRangeHead, // 分数段的标题
                    fractionalRangeData, // 每个班级对应的数据
                    hasFractionalData: filterComparisonData.length > 0 // 新增判断标志
                });

            } else {
                // wx.showToast({
                //     title: res.data.msg || '分数段对比请求失败',
                //     icon: 'none',
                // });
            }
        } catch (error) {
            console.error('分数段对比请求失败:', error);
            // wx.showToast({
            //     title: '分数段对比请求失败',
            //     icon: 'none',
            // });
        }
    },
    // 监听子组件菜单切换事件
    async getOnlineStatus(examId, subjectGroup, endowFlag, classId, subjectId = null) {
        let data = { examId, subjectGroup, endowFlag, classId };
        // 只有 subjectId 有值时才加入
        if (subjectId !== undefined && subjectId !== null && subjectId !== '') {
            data.subjectId = subjectId;
        }
        let options = {
            url: '/analysis/line/online/peopleCompare',
            method: 'get',
            data,
            header: { "content-type": "application/json;charset=UTF-8" },
        };

        try {
            let res = await https(options);
            if (res.data.code === 200) {
                const raw = res.data.data || [];

                // 保存原始数据（没有过滤）
                const originalLinesData = raw.map(obj => {
                    const key = Object.keys(obj)[0];
                    let list = obj[key] || [];
                    return { name: key, list };
                });

                // 处理成 [{name, list}, ...] 结构，并过滤掉特控和二本线中的索引为0的数据
                const linesData = raw.map(obj => {
                    const key = Object.keys(obj)[0];
                    let list = obj[key] || [];


                    const firstClassData = list[0] || {};  // 获取第一个班级数据
                    const firstClassInfo = firstClassData[Object.keys(firstClassData)[0]] || [];  // 获取该班级的数据数组
                    const classInfo = firstClassInfo[0] || {};  // 提取数组中的第一个元素，即班级的实际数据

                    const topData = {
                        onLineScore: classInfo.lineScore || 0,  // 分数线
                        onReferenceNumber: classInfo.peopleNum || 0,  // 参考人数
                        onLineNum: classInfo.fullScoreLineNum || 0,  // 上线人数
                        onLineRate: classInfo.onlineRate || 0,   // 上线率
                        onlineRangeScore: classInfo.onlineRangeScore || 0,   // 临界生区间
                        criticalNum: classInfo.criticalNum || 0, //临界生区间共多少名
                    };

                    // 设置顶部数据
                    this.setData({
                        datainfo: topData,
                    });

                    // 去掉索引为0的数据，用于表格展示
                    list = list.slice(1);


                    return {
                        name: key,
                        list: list  // 班级数据数组
                    };
                });

                // 默认选中第一条
                this.setData({
                    linesData,        // 所有分数线数据
                    originalLinesData, // 保存原始数据
                    currentIndex: 0,  // 默认选中第一条
                    currentIndexs: 0
                });

                // 默认选中后立即更新顶部信息
                this.updateTopInfo(0);  // 直接更新顶部信息，确保初次加载显示正确
            } else {
                // wx.showToast({ title: res.data.msg || '请求失败', icon: 'none' });
            }
        } catch (error) {
            console.error('请求失败:', error);
            // wx.showToast({ title: '请求失败', icon: 'none' });
        }
    },

    // 更新顶部信息
    updateTopInfo(index) {
        console.log("更新顶部信息，索引：", index);

        const linesData = this.data.originalLinesData;  // 使用原始数据
        console.log(linesData, "linesData");

        const selectedLineData = linesData[index]?.list || [];

        // 获取第一个班级数据
        const firstClassData = selectedLineData[0] || {};
        const firstClassInfo = firstClassData[Object.keys(firstClassData)[0]] || [];
        const classInfo = firstClassInfo[0] || {};

        const topData = {
            onLineScore: classInfo.lineScore || 0,  // 分数线
            onReferenceNumber: classInfo.peopleNum || 0,  // 参考人数
            onLineNum: classInfo.fullScoreLineNum || 0,  // 上线人数
            onLineRate: classInfo.onlineRate || 0,   // 上线率
            onlineRangeScore: classInfo.onlineRangeScore || 0,   // 临界生区间
            criticalNum: classInfo.criticalNum || 0, //临界生区间共多少名
        };

        this.setData({
            datainfo: topData,  // 更新顶部信息
        });
    },
    onUpdateIndex(e) {
        const index = e.detail; // 获取选中的菜单索引
        this.setData({
            currentIndex: index
        });

        // 调用封装的更新顶部信息的方法
        this.updateTopInfo(index);
    },

    // onUpdateIndexs(e) {
    //     console.log("点了");

    //     const index = e.detail; // 子组件传的索引
    //     this.setData({
    //         currentIndexs: index,
    //         datainfoS: {
    //             onlineRangeScore: this.data.linesDataS[index]?.rangeStr || "",
    //             criticalNum: this.data.linesDataS[index]?.criticalNum || 0
    //         },
    //         currentList: this.data.linesDataS[index]?.students || []
    //     });
    // },
    onUpdateIndexs(e) {
        const index = e.detail; // 子组件传的索引
        this.setData({
            currentIndexs: index,
            datainfoS: {
                onlineRangeScore: this.data.linesDataS[index]?.rangeStr || "",
                criticalNum: this.data.linesDataS[index]?.criticalNum || 0
            },
        });
    },
    // 更新顶部信息
    updateTopInfos(index) {
        console.log(index, "index");

        const linesData = this.data.originalLinesData;  // 使用原始数据
        const selectedLineData = linesData[index]?.list || [];

        // 获取第一个班级数据
        const firstClassData = selectedLineData[0] || {};
        const firstClassInfo = firstClassData[Object.keys(firstClassData)[0]] || [];
        const classInfo = firstClassInfo[0] || {};

        const topData = {
            onlineRangeScore: classInfo.onlineRangeScore || 0,   // 临界生区间
            criticalNum: classInfo.criticalNum || 0, //临界生区间共多少名
        };

        this.setData({
            datainfos: topData,  // 更新顶部信息
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        const { examId, subjectGroup, classId, selectTypeName } = options;
        console.log("Exam ID:", examId);
        console.log("Subject Group:", subjectGroup);
        console.log("classId", classId);
        console.log(wx.getStorageSync('classInfo'));

        this.setData({
            classInfo: wx.getStorageSync('classInfo'),
            examId,
            subjectGroup,
            selectTypeName,
            classId
        });
        await this.getExamSubjectList(examId, subjectGroup, classId);
        await this.getSchoolScoreCompare(examId, subjectGroup, this.data.endowFlag, classId)
        await this.getSchoolScoreInfo(examId, subjectGroup, this.data.endowFlag, classId)
        await this.getOnlineStatus(examId, subjectGroup, this.data.endowFlag, classId)
        await this.getCriticalStudent(examId, subjectGroup, this.data.endowFlag, classId)
        await this.getScoringAverage(this.data.examId, this.data.subjectGroup, this.data.endowFlag, classId);
        await this.getComparison(this.data.examId, this.data.subjectGroup, this.data.endowFlag, this.data.segmentInterval, this.data.scoreType, classId);
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})